<?php
declare (strict_types=1);

namespace app\command;

use app\api\consDir\CommunityConst;
use app\api\consDir\OrderPrefixConst;
use app\api\consDir\SandConst;
use app\api\services\AlipayService;
use app\api\services\SandService;
use app\common\models\Community\CommunityOrder;
use app\common\models\Order\OrderPay;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use think\facade\Log;
use Yansongda\Pay\Exception\ContainerDependencyException;
use Yansongda\Pay\Exception\ContainerException;
use Yansongda\Pay\Exception\InvalidParamsException;
use Yansongda\Pay\Exception\ServiceNotFoundException;

class CommunityOrderRefund extends Command
{
    protected function configure()
    {
        // 指令配置
        $this->setName('community:order:refund')
            ->setDescription('the community:order:refund command');
    }

    /**
     * @throws InvalidParamsException
     * @throws ContainerDependencyException
     * @throws ServiceNotFoundException
     * @throws ContainerException
     */
    protected function execute(Input $input, Output $output)
    {
        $where = [
            ['status', '=', CommunityConst::ORDER_CANCEL],
            ['create_at', '>', date('Y-m-d')],
            ['is_refund', '=', 0],
            ['is_deal_refund', '<=', 1],
        ];
        $list = CommunityOrder::getInstance()->where($where)->select();
        foreach ($list as $v) {
            //有支付宝订单
            $orderPay = OrderPay::getInstance()->where('order_no', $v['orderNo'])->order('id desc')->find();
            if (empty($orderPay)) {
                continue;
            }
            try {
                //pay_status` tinyint(1) DEFAULT '1' COMMENT '1微信 2支付宝 3余额 4杉德'
                if ($orderPay['payStatus'] == 2) {
                    $aliOrder = AlipayService::getInstance()->find($orderPay['payNo']);
                    if (!empty($aliOrder) && $aliOrder['code'] == 10000) {
                        //退款 更新状态
                        $ret = AlipayService::getInstance()->refund($orderPay['payNo'], $aliOrder['total_amount']);
                        if (!empty($ret) && $ret['code'] == 10000) {
                            $v->is_refund = 1;
                            $v->refund_time = date('Y-m-d H:i:s');
                        }
                    }
                } elseif ($orderPay['payStatus'] == 4) {
                    $price = env('test.is_test') == 1 ? 0.01 : $orderPay['payPrice'];
                    //平台社区
                    $ret = [];
                    if ($v['lastOrderId'] == 0 || $v['is_enough']) {
                        //杉德查询到消费订单
                        $orderQuery = SandService::getInstance()->orderQuery($orderPay['payNo']);
                        if (isset($orderQuery['orderStatus']) && $orderQuery['orderStatus'] == 'success') {
                            $ret = SandService::getInstance()->orderRefund(getNo(OrderPrefixConst::RF), $orderPay['payNo'], $price);
                        }
                    } else {
                        //转让的社区
                        $userId = CommunityOrder::getInstance()->where('id', $v['lastOrderId'])->value('user_id');
                        $ret = SandService::getInstance()->transferConfirm(getNo(OrderPrefixConst::TC), $orderPay['payNo'], $price, 'cancel', SandConst::PREFIX . $userId);
                        Log::info('取消转账' . json_encode($ret, 256));
                    }
                    if (isset($ret['resultStatus']) && $ret['resultStatus'] == 'success') {
                        $v->is_refund = 1;
                        $v->refund_time = date('Y-m-d H:i:s');
                    }
                }
                $v->is_deal_refund = $v->is_deal_refund + 1;
                $v->save();
            } catch (\Exception $e) {
                Log::error($v['orderNo'] . $e->getMessage());
            }

        }

        // 指令输出
        $output->writeln('community:order:refund');
    }
}
